package com.cwt.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwt.common.result.AjaxResult;
import com.cwt.common.utils.DateUtils;
import com.cwt.service.domain.ShopCar;
import com.cwt.service.service.ShopCarService;
import com.cwt.service.mapper.ShopCarMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
* @author Acer
* @description 针对表【tb_shop_car(商品购物车)】的数据库操作Service实现
* @createDate 2023-08-02 16:12:50
*/
@Service
public class ShopCarServiceImpl extends ServiceImpl<ShopCarMapper, ShopCar>
    implements ShopCarService{

    @Override
    public AjaxResult addShopCar(ShopCar car) {
        QueryWrapper<ShopCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "user_id", car.getUserId());
        queryWrapper.eq(true, "book_id", car.getBookId());
        ShopCar existCar = baseMapper.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(existCar)) {
            car.setCreateTime(DateUtils.formatFullDateTime(new Date()));
            car.setUpdateTime(DateUtils.formatFullDateTime(new Date()));
            car.setTotalPrice(String.valueOf(Integer.parseInt(car.getBookPrice()) * car.getCount()));
            return baseMapper.insert(car) > 0
                    ? AjaxResult.success(car.getBookName() + " 书籍添加购物车成功！")
                    : AjaxResult.error(car.getBookName() + " 书籍添加购物车失败！");
        }

        // 已存在，数量 + 1
        existCar.setCount(existCar.getCount() + 1);
        existCar.setTotalPrice(String.valueOf(existCar.getCount() * Integer.parseInt(existCar.getBookPrice())));
        return baseMapper.updateById(existCar) > 0
                ? AjaxResult.success(car.getBookName() + " 书籍添加购物车成功！")
                : AjaxResult.error(car.getBookName() + " 书籍添加购物车失败！");
    }

    @Override
    public long countByUser(long userId) {
        QueryWrapper<ShopCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "user_id", userId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public AjaxResult reduceShopCar(ShopCar car) {
        car.setCount(car.getCount() - 1);
        car.setTotalPrice(String.valueOf(car.getCount() * Integer.parseInt(car.getBookPrice())));
        if (car.getCount() == 0) {
            return baseMapper.deleteById(car) > 0
                    ? AjaxResult.success(car.getBookName() + " 购物车数据移除成功！")
                    : AjaxResult.error(car.getBookName() + " 购物车数据移除失败！");
        }
        return baseMapper.updateById(car) > 0
                ? AjaxResult.success(car.getBookName() + " 购物车数据移除成功！")
                : AjaxResult.error(car.getBookName() + " 购物车数据移除失败！");
    }
}




